package com.hlkj.warboot.configurer.util;

import com.alibaba.fastjson.JSONObject;
import com.hlkj.warboot.configurer.util.base.BaseExceptionUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.MessageFormat;

/**
 * @Description: TODO 请求数据响应工具类
 * @Author: 李星 lixing_java@163.com
 * @Date: 2019/10/10 21:15
 */
public class ResponseUtil {
    /*
     * @Description TODO 成功响应
     * @Author 李星
     * @Date 2019/7/27 15:06
     * @Param []
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject success() {
        return success(null);
    }

    /*
     * @Description TODO 成功响应
     * @Author 李星
     * @Date 2019/7/27 15:06
     * @Param []
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject success(Object data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("message", "操作成功");
        jsonObject.put("data", data);
        return jsonObject;
    }

    /*
     * @Description TODO 失败响应
     * @Author 李星
     * @Date 2019/7/27 15:06
     * @Param []
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject fail(String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 1);
        jsonObject.put("message", message);
        return jsonObject;
    }

    /*
     * @Description TODO 输出JSON字符串到浏览器
     * @Author 李星
     * @Date 2019/6/29 22:47
     * @Param [response, responseObject]
     * @return void
     */
    public static void outputJson(HttpServletResponse response, Object responseObject) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = null;
        try {
            String jsonString = JSONObject.toJSONString(responseObject);
            printWriter = response.getWriter();
            printWriter.write(jsonString);
            printWriter.flush();
        } catch (IOException e) {
            LoggerUtil.error(MessageFormat.format("输出JSON字符串到前台出错: {0}\n", e.getMessage()));
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /*
     * @Description TODO 输出Excel2003、Excel2007文件到浏览器
     * @Author 李星
     * @Date 2019/10/10 21:46
     * @Param [sxssfWorkbook 工作簿, excelType 扩展名, excelName 名称, response HttpServletResponse]
     * @return void
     */
    public static void outputExcelFile(SXSSFWorkbook sxssfWorkbook, String excelType, String excelName, HttpServletResponse response) throws IOException {
        switch (excelType) {
            case ".xls":
                response.setContentType( "application/vnd.ms-excel" );
                break;
            case ".xlsx":
                response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
                break;
            default:
                throw new BaseExceptionUtil("Excel类型无效");
        }

        response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode( excelName + excelType, "utf-8" ) );
        try (OutputStream outputStream = response.getOutputStream()) {
            sxssfWorkbook.write(outputStream); // 将Excel对象写入字节流
            outputStream.flush();
            outputStream.close();
            sxssfWorkbook.dispose();
            sxssfWorkbook.close();
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("输出Excel文件到浏览器出错：{0}", e.getMessage()));
        } finally {
            if (sxssfWorkbook != null) {
                sxssfWorkbook.dispose(); // 释放临时文件
                sxssfWorkbook.close();
            }
        }
    }

    /*
     * @Description TODO 输出文件到浏览器
     * @Author 李星
     * @Date 2019/10/10 21:46
     * @Param [response HttpServletResponse, file 文件对象, fileName 文件名称]
     * @return void
     */
    public static void outputFile(HttpServletResponse response, File file, String fileName) throws IOException {
        response.setContentType("multipart/form-data");
        response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode( fileName, "utf-8" ) );
        //
        OutputStream outputStream = response.getOutputStream();
        byte[] buf = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int readBytesLen; // 读取字节的长度
            while ((readBytesLen = bis.read(buf)) != -1) {
                outputStream.write(buf,0, readBytesLen);
            }
            outputStream.flush();
        } catch (Exception e) {
            //LoggerUtil.error(MessageFormat.format("输出Excel文件到浏览器出错：{0}", e.getMessage()));
        } finally {
            try {
                assert outputStream != null;
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                assert bis != null;
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
